package struts;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import struts.form.XmlBean;

public class StrutsConfig {

	public static Map<String, XmlBean> StrutsConfig(String strutsConfigPath) throws Exception {
		SAXBuilder xmlBuilder = new SAXBuilder();
		Document document = xmlBuilder.build(new File(strutsConfigPath));
		Element root = document.getRootElement();
		Map<String, XmlBean> xmlBeans = new HashMap<String, XmlBean>();
		// Element formBeans = root.getChild("formbeans");
		// List<Element> forms = formBeans.getChildren();
		// for (Element formbean : forms) {
		// String formBeanName = formbean.getAttributeValue("name");
		// String formBeanClass = formbean.getAttributeValue("class");
		// }

		Element actionMapping = root.getChild("action-mapping");
		List<Element> actions = actionMapping.getChildren();
		for (Element action : actions) {
			XmlBean xmlBean = new XmlBean();
			String actionName = action.getAttributeValue("name");
			xmlBean.setActionName(actionName);

			xmlBean.setActionPath(action.getAttributeValue("path"));
			Element formBeans = root.getChild("formbeans");
			List<Element> forms = formBeans.getChildren();
			for (Element form : forms) {
				if (actionName.equals(form.getAttributeValue("name"))) {
					String formBeanClass = form.getAttributeValue("class");
					xmlBean.setFormBeanClass(formBeanClass);
					break;
				}
			}

			String actionType = action.getAttributeValue("type");
			xmlBean.setActionType(actionType);
			String actionPath = action.getAttributeValue("path");
			xmlBean.setActionPath(actionPath);

			Map<String, String> forwardMap = new HashMap<String, String>();
			List<Element> forwards = action.getChildren();
			for (Element forward : forwards) {
				String forwardName = forward.getAttributeValue("name");
				String forwardValue = forward.getAttributeValue("value");
				forwardMap.put(forwardName, forwardValue);
			}
			xmlBean.setActionForward(forwardMap);
			xmlBeans.put(actionPath, xmlBean);
		}
		return xmlBeans;
	}
}
